package com.redwine.app.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.redwine.app.APP;
import com.redwine.app.MyPublishedSourcesUpdateActivity;
import com.redwine.app.R;
import com.redwine.app.net.GsonRequest;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.responses.BaseResponse;
import com.redwine.app.net.responses.SendMsgEvent;
import com.redwine.app.net.responses.SendPublishResponse;
import com.redwine.app.utils.BitmapUtils;
import com.redwine.app.utils.DimenUtils;
import com.redwine.app.utils.Utils;
import com.redwine.app.view.AlertDialog;
import com.redwine.app.view.PopupListWindow;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * 我发布的货源配器
 * 作者：gassion on 17/7/27 14:38
 * 最可怕的敌人，就是没有坚强的信念。
 */
public class MySendPublishAdapter extends BaseAdapter {

    private Context context;

    private List<SendPublishResponse.DataEntityX.DataEntity> datalist;


    public MySendPublishAdapter(Context context) {
        this.context = context;
    }


    /**
     * 下拉加载数据
     *
     * @param datalist
     */
    public void setData(int page, List<SendPublishResponse.DataEntityX.DataEntity> datalist) {
        if (page > 1) {
            if (null != this.datalist && !this.datalist.isEmpty())
                this.datalist.addAll(datalist);

        } else {
            if (null != this.datalist && !this.datalist.isEmpty())
                this.datalist = new ArrayList<>();
            this.datalist = datalist;
        }
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        if (null != datalist) {
            return datalist.size();
        } else {
            return 0;
        }
    }

    @Override
    public Object getItem(int position) {
        if (null != datalist) {
            return datalist.get(position);
        } else {
            return null;
        }
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            LayoutInflater layoutInflater = LayoutInflater.from(context);
            convertView = layoutInflater.inflate(R.layout.activity_my_send_publish_item, parent, false);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        final SendPublishResponse.DataEntityX.DataEntity dataEntity = datalist.get(position);
        List<String> strings = Utils.strConvertList(dataEntity.getPic());
        if (null != strings && !strings.isEmpty())
            BitmapUtils.loadImage(viewHolder.mMySendPublishIvPic, strings.get(0), BitmapUtils.THE_ARTICLE);
        viewHolder.mMySendPublishTvName.setText(dataEntity.getName());
        viewHolder.mMySendPublishTvTime.setText(dataEntity.getDate());
        viewHolder.mMySendPublishTvPrice.setText(dataEntity.getPrice());
        viewHolder.mMySendPublishTvMessageCount.setText(dataEntity.getMessage_count() + "人留言");
        Utils.setSupplierStatus(viewHolder.mMySendPublishTvAdoptStatus, Integer.valueOf(dataEntity.getStatusX()));
        viewHolder.mMySendPublishTvMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<String> data = new ArrayList<>();
                data.add("删除");
                data.add("修改");
                data.add("停止供应");
                PopupListWindow popupListWindow = new PopupListWindow(context, data);
                popupListWindow.setOnClickListener(new PopupListWindow.OnClickListener() {
                    @Override
                    public void onClick(int position) {
                        switch (position) {
                            case 0:
                                confirmDialog(dataEntity.getId(), position);
                                break;

                            case 1:
                                Intent intent = new Intent(context, MyPublishedSourcesUpdateActivity.class);
                                intent.putExtra(MyPublishedSourcesUpdateActivity.PUBLISH_ID, dataEntity.getId());
                                context.startActivity(intent);
                                break;

                            case 2:
                                //停止供应
                                requestPublishEndData(dataEntity.getId());
                                break;

                        }
                    }
                });
                popupListWindow.showAsDropDown(v, DimenUtils.dip2px(-19), DimenUtils.dip2px(15));
            }
        });
        return convertView;
    }

    public static class ViewHolder {
        public View rootView;
        public TextView mMySendPublishTvTime;
        public TextView mMySendPublishTvMore;
        public ImageView mMySendPublishIvPic;
        public TextView mMySendPublishTvName;
        public TextView mMySendPublishTvPrice;
        public TextView mMySendPublishTvMessageCount;
        public TextView mMySendPublishTvAdoptStatus;

        public ViewHolder(View rootView) {
            this.rootView = rootView;
            this.mMySendPublishTvTime = (TextView) rootView.findViewById(R.id.my_send_publish_tv_time);
            this.mMySendPublishTvMore = (TextView) rootView.findViewById(R.id.my_send_publish_tv_more);
            this.mMySendPublishIvPic = (ImageView) rootView.findViewById(R.id.my_send_publish_iv_pic);
            this.mMySendPublishTvName = (TextView) rootView.findViewById(R.id.my_send_publish_tv_name);
            this.mMySendPublishTvPrice = (TextView) rootView.findViewById(R.id.my_send_publish_tv_price);
            this.mMySendPublishTvMessageCount = (TextView) rootView.findViewById(R.id.my_send_publish_tv_message_count);
            this.mMySendPublishTvAdoptStatus = (TextView) rootView.findViewById(R.id.my_send_publish_tv_adopt_status);
        }

    }

    /**
     * 停止供应
     */
    private void requestPublishEndData(String purchaseId) {
        String url = NetworkConstants.DELETE_PUBLISH_END_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("publish_id", purchaseId);
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST,
                BaseResponse.class, false, params, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                if (response.isSuccess()) {
                    EventBus.getDefault().post(new SendMsgEvent(SendMsgEvent.REFURBISH_PUBLISHDE_LIST));
                } else {
                    Utils.showToast(response.getMsg());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Utils.showToast(error.getMessage());
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }


    /**
     * 我发布的货源删除
     */
    private void requestDeleteData(String purchaseId, final int position) {
        String url = NetworkConstants.DELETE_PUBLISH_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("publish_id", purchaseId);
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST,
                BaseResponse.class, false, params, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                if (response.isSuccess()) {
                    datalist.remove(position);
                    notifyDataSetChanged();
                    EventBus.getDefault().post(new SendMsgEvent(SendMsgEvent.REFURBISH_PUBLISHDE_LIST));
                } else {
                    Utils.showToast(response.getMsg());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Utils.showToast(error.getMessage());
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    /**
     * 删除确认提示框
     *
     * @param purchaseId
     * @param position
     */
    private void confirmDialog(final String purchaseId, final int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(context.getString(R.string.hint));
        builder.setMessage(context.getString(R.string.hint_delete_this_resource));
        builder.setNegativeButton(context.getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton(context.getString(R.string.confirm), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                requestDeleteData(purchaseId, position);
            }
        });
        AlertDialog mDialog = builder.create();
        mDialog.setCancelable(false);
        mDialog.show();
    }
}
